<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2020-06-17
 * Time: 16:24
 * 项目查看订单管理
 */

namespace app\api\service\project;

use app\api\model\ProjectHatchLookOrder;
use app\api\model\System;
use app\api\service\Token;
use app\lib\exception\ParameterException;
use think\Db;
use think\Exception;

class LookOrderSer extends Token
{
    /**
     * 1.判断用户信息
     * 2.判断是否有查看的权限
     * 3.有进行提示
     * 4.没有添加订单  返回支付number
     */

    // 用户ID
    private $uid;

    // 项目孵化ID
    private $projectHatchId;

    function __construct($projectHatchId)
    {
        $this->projectHatchId = $projectHatchId;
        $this->uid = self::getCurrentUid();
        self::judgeMember();
    }

    // 入口方法
    public function entrance()
    {
        return $this->judgeProjectLook();
    }

    // 判断查看权限
    private function judgeProjectLook()
    {
        $info = self::judgeProjectHatchLook($this->projectHatchId);
        if($info) {
            throw new ParameterException([
                'errorCode' => 20006,
                'msg' => [
                    'hatch' => '您有项目查看的权限'
                ]
            ]);
        }
        return $this->createOrder();
    }

    // 创建订单信息
    private function createOrder()
    {
        // 删除未支付的订单
        ProjectHatchLookOrder::destroy(['user_id' => $this->uid, 'status' => 1 ]);
        $system = System::get(1);
        // 创建订单
        Db::startTrans();
        try{
            $mode = ProjectHatchLookOrder::create([
                'user_id' => $this->uid,
                'price' => $system['project_hatch_look_price'],
                'order_no' => self::makeOrderNo(),
            ]);
            $out_trade_no = '5you2020'.$mode->id;
            $mode->out_trade_no = $out_trade_no;
            $mode->save();
            Db::commit();
            return writeJson(201, [ 'out_trade_no' => $out_trade_no ], '订单生成成功！');
        }
        catch (Exception $ex) {
            Db::rollback();
            throw $ex;
        }
    }
}